package it.softphone.cmc.server.entity;

import it.softphone.cmc.server.service.EntityManagerBaseService.EMTask;
import it.softphone.cmc.server.service.exception.CMCException;
import it.softphone.cmc.server.service.impl.GAESystemManagerServiceImpl;
import it.softphone.cmc.server.service.listener.AccountPreferenceEntityListener;
import it.softphone.cmc.shared.entity.Account;
import it.softphone.cmc.shared.entity.Tenant;
import it.softphone.commons.spring.ApplicationConfig;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;


import com.google.appengine.api.datastore.Key;

@SuppressWarnings("serial")
@Entity
@EntityListeners(AccountPreferenceEntityListener.class)
public class AccountPreferenceEntity implements Account.Preference, Serializable {


	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id private Key key;

	@Basic Key accountRef;
	@Basic Key tenantRef;
	
	@Transient Tenant tenant;
	
	public final Key getKey() {
		return key;
	}
	public final void setKey(Key key) {
		this.key = key;
	}
	
	public final Key getAccountRef() {
		return accountRef;
	}
	public final void setAccountRef(Key account) {
		this.accountRef = account;
	}
	public final Key getTenantRef() {
		return tenantRef;
	}
	public final void setTenantRef(Key tenant) {
		this.tenantRef = tenant;
	}
	
	@Override
	public final Tenant getTenant() {
		return tenant;
	}
	
	@Override
	public final void setTenant(Tenant tenantObject) {
		this.tenant = tenantObject;
	}

	/**
	 * Actually post load doesn't work through listener
	 *
	 * We have to call this method by hand :-(
	 * 
	 * @throws CMCException
	 */
    //@PostLoad 
    public final void postLoad() throws CMCException {
    	if( tenant != null ) return;
    	
    	GAESystemManagerServiceImpl system = ApplicationConfig.getBean(GAESystemManagerServiceImpl.class);
    	
    	TenantEntity tenant = system.exec( "retrive tenant from preferences", new EMTask<TenantEntity>() {

			@Override
			public TenantEntity exec(EntityManager em) throws Exception {

				return em.find(TenantEntity.class, getTenantRef());
			}
    		
		});
    	
    	setTenant(tenant);
    }
	

}
